package com.mtons.mblog.modules.job;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_MINUTE_FORMATTER;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mtons.mblog.base.utils.HttpUtils;
import com.mtons.mblog.base.utils.MD5;
import com.mtons.mblog.modules.data.CreVO;
import com.mtons.mblog.modules.data.DingTalkMd;
import com.mtons.mblog.modules.data.DingTalkMsg;
import com.mtons.mblog.modules.data.DingTalkResponse;
import com.mtons.mblog.modules.entity.Options;
import com.mtons.mblog.modules.service.LearnDocService;
import com.mtons.mblog.modules.service.OptionsService;
import java.util.Date;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 学习任务定时任务
 */
@Component
@Slf4j
public class LearnJob {

  @Resource
  private LearnDocService learnDocService;
  @Resource
  private OptionsService optionsService;

  public static boolean startFlag = true;

  public static int lastVal = 0;

  public static int maxShowCount = 2;

  public static int nextVal = 0;

  public static Map<Integer,Integer> showMap = new HashMap<Integer,Integer>(){
    {
      put(0,0);
      put(1,0);
      put(2,0);
      put(3,0);
      put(4,0);
      put(5,0);
      put(6,0);
      put(7,0);
      put(8,0);
      put(9,0);
      put(10,0);
    }
  };


  private static String cookieTemp;

  //  @Scheduled(cron = "*/15 * * * * ?")
  public void initNeedReview() {
    int reviewCount = learnDocService.reviewDoc();
    if (reviewCount > 0) {
      log.info("当前共有{}个文档需要复习初始化", reviewCount);
    }
  }

  private AtomicBoolean flag = new AtomicBoolean(false);

  //  @Scheduled(cron = "*/15 * * * * ?")
  public void sendReviewEmail() {
    int reviewCount = learnDocService.sendReviewEmail();
    if (reviewCount > 0) {
      log.info("当前共有{}个文档已经发送邮箱进行提醒", reviewCount);
    }
  }

  //    @Scheduled(cron = "* 0/10 * * * ? ")
  public void ddMsg() {
    HashMap dataMap = new HashMap();
    dataMap.put("isAjax", "true");
    try {
      String json = HttpUtils.post(
          "http://www.95572.com/cre/order!getListByorderno.action?billCode=K05011368456&type=1",
          dataMap);
      CreVO creVOS = JSONArray.parseObject(json, CreVO.class);
      if (creVOS != null && creVOS.getSuccess()) {
        String data = creVOS.getData();
        String md5 = MD5.md5(data);
        List<Options> all = optionsService.findAll();
        all.forEach(vo -> {
          String key = vo.getKey();
          if (key.equals("cre_md5")) {
            String value = vo.getValue();
            if (!md5.equals(value)) {
              updateMsg(data, md5);
            }
          }
        });
        if (flag.compareAndSet(false, true)) {
          updateMsg(data, md5);
        }
      }
    } catch (Exception e) {
      log.info("发送中铁快运信息时出现异常", e);
    }

  }

  private void updateMsg(String data, String md5) {
    HashMap<String, String> options = new HashMap<>();
    options.put("cre_md5", md5);
    Document document = Jsoup.parse(data);
    Elements detail = document.select("[class=left]");
    Elements nowElements = detail.get(0).select("p");
    int size = nowElements.size();
    StringBuilder contentMsgBuilder = new StringBuilder();
    contentMsgBuilder.append("# 中铁速运 \n");
    contentMsgBuilder.append("## 最新信息 \n");
    for (int i = 0; i < size; i++) {
      Element element = nowElements.get(i);
      String text = element.text();
      contentMsgBuilder.append(">  ");
      contentMsgBuilder.append(text);
      contentMsgBuilder.append("\r\n");
    }
    contentMsgBuilder.append("## 具体流转记录 \r\n");
    String newMsg = detail.html();
    Elements contentDoc = document.select("[class=list-jl]");
    String contentMsg = contentDoc.html();
    Element element = contentDoc.get(0);
    Elements infoElements = element.getElementsByTag("p");
    int nowLen = infoElements.size();
    for (int i = 0; i < nowLen; i++) {
      Element tempEle = infoElements.get(i);
      Elements spanElements = tempEle.getElementsByTag("span");
      contentMsgBuilder.append(spanElements.get(0).text());
      contentMsgBuilder.append("  ");
      contentMsgBuilder.append(spanElements.get(1).text());
      contentMsgBuilder.append("  ");
      contentMsgBuilder.append(spanElements.get(2).text());
      contentMsgBuilder.append("\r\n");
      contentMsgBuilder.append("---");
      contentMsgBuilder.append("\r\n");
    }
    String result = newMsg + "<br/>" + contentMsg;
    DingTalkMsg dingTalkMsg = new DingTalkMsg();
    dingTalkMsg.setMsgtype("markdown");
    DingTalkMd markdown = new DingTalkMd();
    markdown.setTitle("中铁快运");
    markdown.setText(contentMsgBuilder.toString());
    dingTalkMsg.setMarkdown(markdown);
    String dingTalkStr = JSONObject.toJSONString(dingTalkMsg);
//        Map<String,String> dingDataMap = JSON.parseObject(dingTalkStr, Map.class);
    try {
      String post = HttpUtils.postObj(
          "https://oapi.dingtalk.com/robot/send?access_token=e4312cdbf6795bcc0f104c91e6a612154100e29a27521f2cace4f8872ee900b7",
          dingTalkStr);
      DingTalkResponse dingTalkResponse = JSON.parseObject(post, DingTalkResponse.class);
      if (dingTalkResponse != null && dingTalkResponse.getErrcode() == 310000) {
        log.warn("调用钉钉返回错误，信息为{}", post);
      } else {
        optionsService.update(options);
      }
    } catch (Exception e) {
      log.error("调用钉钉有问题", e);
    }
  }

//  @Scheduled(cron = "0 */10 * * * * ")
  public void gps() {
    if (!startFlag) {
      log.info("不开启监测");
//      sendDingTalk("中铁快运", "不开启电量监测");
      return;
    } else {
      log.info("正在监测电量");
//      sendDingTalk("中铁快运", "开启电量监测");
    }
    try {
      // 登录页面地址
      String loginPageUrl = "http://www.yugps.com/Account/Login?ReturnUrl=%2F";
      // 登录请求参数
      String loginUrl = "http://www.yugps.com/Account/Login";
      String loginJson = "{\"userName\":\"18911222574\",\"password\":\"222204\",\"loginType\":\"UserNameAndPassword\"}";

      // 获取数据请求参数
      String dataUrl = "http://www.yugps.com/Position/GetMonitorData";
      String dataJson = "{\"skipCount\":0,\"maxResultCount\":10,\"searchText\":\"\",\"searchType\":\"all\",\"deviceGroupId\":\"\",\"coordinates\":\"Gcj02\"}";

      if (StrUtil.isEmpty(cookieTemp)) {
        // 发送GET请求获取Cookie
        HttpResponse loginPageResponse = HttpRequest.get(loginPageUrl).execute();
        String cookie = loginPageResponse.getCookieStr();
        // 使用Cookie发送登录请求
        HttpResponse loginResponse = HttpRequest.post(loginUrl)
            .header("Cookie", cookie)
            .body(loginJson)
            .execute();
        cookieTemp = cookie;
        String loginResult = loginResponse.body();
        if (loginResponse.getStatus() != 200) {
          log.info("Login failed!");
          sendDingTalk("中铁快运", "开启电量监测发现系统可能无法访问");
          cookieTemp = null;
          return;
        }
        log.info("定时，此次进行登陆");
      }
      // 判断登录是否成功，这里简单通过状态码判断，具体根据实际情况进行修改
      // 使用Cookie发送请求获取数据
      HttpResponse dataResponse = HttpRequest.post(dataUrl)
          .header("Cookie", cookieTemp)
          .body(dataJson)
          .execute();
      String resultJson = dataResponse.body();

      // 解析结果并提取所需数据
      cn.hutool.json.JSONObject resultObj = JSONUtil.parseObj(resultJson);
      cn.hutool.json.JSONArray itemsArray = resultObj.getJSONObject("result")
          .getJSONArray("items");
      cn.hutool.json.JSONObject itemObj = itemsArray.getJSONObject(0);
      String winDeviceStatusText = itemObj.getStr("winDeviceStatusText");
      //已设防 电量76% 电压67.5V 信号21
      if (StrUtil.isNotEmpty(winDeviceStatusText)) {
        String[] resultArr = winDeviceStatusText.split(" ");
        if (resultArr.length > 2) {
          String tempStatus = resultArr[1].substring(2, 4);
          int numberStatus = Integer.parseInt(tempStatus);
          int level = numberStatus / 10;
          Integer count = showMap.get(level);
          if(count < maxShowCount){
            sendDingTalk("中铁快运",
                "正在充电，当前电量为：" + numberStatus + "发生时间：" + DateUtil.format(new Date(),
                    NORM_DATETIME_MINUTE_FORMATTER));
            showMap.put(level,++count);
          }
          if(numberStatus == lastVal){
            sendDingTalk("中铁快运",
                "当前电量为" + numberStatus + "，一直未变化，有可能已经断电了" + "发生时间：" + DateUtil.format(
                    new Date(), NORM_DATETIME_MINUTE_FORMATTER));
          }else {
            lastVal = numberStatus;
          }
          if (numberStatus >= 99) {
              sendDingTalk("中铁快运", "当前已经充满电了,电量"+ numberStatus + "发生时间：" + DateUtil.format(new Date(),
                  NORM_DATETIME_MINUTE_FORMATTER));
            startFlag = false;
            lastVal = 0;
          }
          log.info("电量：" + numberStatus);
        } else {
          log.info("解析异常");
        }
      }
      // 输出所需数据
      log.info("winDeviceStatusText: " + winDeviceStatusText);
    } catch (Exception ex) {
      log.error("定位出错", ex);
      sendDingTalk("中铁快运", ex.getMessage());
      cookieTemp = null;
    }
  }

  public void sendDingTalk(String title, String content) {
    DingTalkMsg dingTalkMsg = new DingTalkMsg();
    dingTalkMsg.setMsgtype("markdown");
    DingTalkMd markdown = new DingTalkMd();
    markdown.setTitle(title);
    markdown.setText(content);
    dingTalkMsg.setMarkdown(markdown);
    String dingTalkStr = JSONObject.toJSONString(dingTalkMsg);
    try {
      String post = HttpUtils.postObj(
          "https://oapi.dingtalk.com/robot/send?access_token=e4312cdbf6795bcc0f104c91e6a612154100e29a27521f2cace4f8872ee900b7",
          dingTalkStr);
      DingTalkResponse dingTalkResponse = JSON.parseObject(post, DingTalkResponse.class);
      if (dingTalkResponse != null && dingTalkResponse.getErrcode() == 310000) {
        log.warn("调用钉钉返回错误，信息为{}", post);
      }
    } catch (Exception e) {
      log.error("调用钉钉有问题:" + title, e);
    }
  }

}
